package Ventanas;

import Objetos.PropiedadesIP;
import Proxies.CtrlChatWS;
import Proxies.CtrlChatWSService;
import Proxies.CtrlRelojSistemaWSService;
import Proxies.CtrlUsuariosWS;
import Proxies.CtrlUsuariosWSService;
import Proxies.DataMensaje;
import Proxies.DataMensajeArray;
import Proxies.DataUsuario;
import Proxies.StringArray;
import java.awt.Font;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.xml.namespace.QName;

public class Conversacion extends javax.swing.JDialog {

    private String mailUsr;
    private int idChat;
    private ArrayList<DataMensaje> bandejaSalida;
    private Principal principal;
//    private ArrayList<DataMensaje> historialLocal;
    

    public Conversacion(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public Conversacion(java.awt.Frame parent, boolean modal, String mail, int idchat, Principal princ) {
        super(parent, modal);
        initComponents();
        mailUsr = mail;
        this.idChat = idchat;
        DefaultListModel model = new DefaultListModel();
        jList1.setModel(model);
        Leer hilo = new Leer();
        hilo.start();
        charla.setText(mailUsr);
        bandejaSalida = new ArrayList<DataMensaje>();
        principal = princ;
//        historialLocal = new ArrayList<DataMensaje>();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        mensaje = new javax.swing.JTextField();
        recibir = new javax.swing.JButton();
        charla = new javax.swing.JLabel();
        Abandonar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Conversacion");

        jScrollPane1.setViewportView(jList1);

        jButton1.setText("Enviar");
        jButton1.setFocusCycleRoot(true);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        mensaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mensajeActionPerformed(evt);
            }
        });

        recibir.setText("Invitar amigos al chat");
        recibir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                recibirActionPerformed(evt);
            }
        });

        Abandonar.setText("Abandonar Chat");
        Abandonar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AbandonarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
                                .addGap(79, 79, 79))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(mensaje, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(recibir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(charla, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Abandonar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(charla, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                    .addComponent(recibir, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(Abandonar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(mensaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        String mens = mensaje.getText().toString();
        DataMensaje dMens = new DataMensaje();

        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dirChat = null;
        try {
            dirChat = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNaChat = new QName("http://WebServices/", "CtrlChatWSService");
        CtrlChatWS chat = new CtrlChatWSService(dirChat, qNaChat).getCtrlChatWSPort();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlRelojSistema?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlRelojSistemaWSService");

        dMens.setFecha(new CtrlRelojSistemaWSService(dir, qNa).getCtrlRelojSistemaWSPort().getTime());

        dMens.setEmisor(mailUsr);
        dMens.setMsj(mens);
        if (!chat.finalizo(String.valueOf(idChat))) {
            if (principal.isConectado()) {
                chat.send(dMens, idChat);
//                historialLocal.add(dMens);
                
            } else {
                bandejaSalida.add(dMens);
                DefaultListModel mod = (DefaultListModel) jList1.getModel();
                mod.add(mod.getSize(), "Sin conexion con el Servidor, guardado en bandeja de salida.");
            }
        } else {
            DefaultListModel mod = (DefaultListModel) jList1.getModel();
            mod.add(mod.getSize(), "El chat termino");

        }
//        DefaultListModel model = (DefaultListModel) jList1.getModel();
//        model.add(model.getSize(),mailUsr+"\n dice : \n"+ mens);
        mensaje.setText("");


    }//GEN-LAST:event_jButton1ActionPerformed

    private void mensajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mensajeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_mensajeActionPerformed

    private void recibirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recibirActionPerformed
        // TODO add your handling code here:
        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dirChat = null;
        try {
            dirChat = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNaChat = new QName("http://WebServices/", "CtrlChatWSService");
        CtrlChatWS chat = new CtrlChatWSService(dirChat, qNaChat).getCtrlChatWSPort();
        
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlUsuarios?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlUsuariosWSService");
        CtrlUsuariosWS usu = new CtrlUsuariosWSService(dir, qNa).getCtrlUsuariosWSPort();
        StringArray listPart = chat.getParticipantes(String.valueOf(idChat));
        
         StringArray amigosEnComun = usu.amigosEnComun(listPart);

        InvitarAmigos inv = new InvitarAmigos(null, false, this, amigosEnComun);
        inv.setVisible(true);
        inv.setLocationRelativeTo(null);

    }//GEN-LAST:event_recibirActionPerformed

    private void AbandonarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AbandonarActionPerformed
        // TODO add your handling code here:
        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dirChat = null;
        try {
            dirChat = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNaChat = new QName("http://WebServices/", "CtrlChatWSService");
        CtrlChatWS chat = new CtrlChatWSService(dirChat, qNaChat).getCtrlChatWSPort();

        URL dir = null;
        try {
            dir = new URL(IP + "CtrlUsuarios?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlUsuariosWSService");
        CtrlUsuariosWS usu = new CtrlUsuariosWSService(dir, qNa).getCtrlUsuariosWSPort();
        StringArray cantPart = chat.getParticipantes(String.valueOf(idChat));
      
        
        DataMensajeArray historial = chat.getHistorial(String.valueOf(idChat));
        
        Iterator<String> it = chat.getParticipantes(String.valueOf(idChat)).getItem().iterator();
        while(it.hasNext()){
            
            String amigo = it.next();
            if(!amigo.equals(mailUsr))
            usu.agegarHistorial(mailUsr,amigo,historial);
        }
        Iterator<String> it2 = chat.getParticipantes(String.valueOf(idChat)).getItem().iterator();
        while(it2.hasNext()){
            
            String user = it2.next();
            usu.agegarHistorial(user,mailUsr,historial);
        }
      
//        principal.agregarHistorialLocal(chat.getParticipantes(String.valueOf(idChat)),historialLocal);
        abondanarChat(mailUsr);
        JOptionPane.showMessageDialog(null, "Se abandono el chat");
        setVisible(false);
        
    }//GEN-LAST:event_AbandonarActionPerformed

    public StringArray getParticpantesChat(){
        
        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dirChat = null;
        try {
            dirChat = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNaChat = new QName("http://WebServices/", "CtrlChatWSService");
        CtrlChatWS chat = new CtrlChatWSService(dirChat, qNaChat).getCtrlChatWSPort();

        return chat.getParticipantes(String.valueOf(idChat));
    }
    /**
     * @param args the command line arguments
     */
    private void leer() {

        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlChatWSService");
       CtrlChatWS chat = new  CtrlChatWSService(dir, qNa).getCtrlChatWSPort();
        DataMensaje recibe = chat.recibe(mailUsr, idChat);
        URL dirUsr = null;
        try {
            dirUsr = new URL(IP + "CtrlUsuarios?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNaUsr = new QName("http://WebServices/", "CtrlUsuariosWSService");
        CtrlUsuariosWS ctrlUsr = new CtrlUsuariosWSService(dirUsr, qNaUsr).getCtrlUsuariosWSPort();
        
        DefaultListModel model = (DefaultListModel) jList1.getModel();
         if(!principal.isConectado())
            return;
        int tam = model.getSize();
        if (recibe != null) {
            model.add(tam, "<html><b>" + ctrlUsr.getUsuario(recibe.getEmisor()).getNombre() + ": </b> " + recibe.getMsj() + "</html>");
            principal.agregarMensajeLocal(chat.getParticipantes(String.valueOf(idChat)), recibe);
            jList1.setModel(model);
        }
        
        jList1.setFont(jList1.getFont().deriveFont(Font.PLAIN));

    }

    public void agregarInvitado(String invitado) {
        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlChatWSService");
        CtrlChatWS ctrl = new CtrlChatWSService(dir, qNa).getCtrlChatWSPort();
        ctrl.agregarAmigoAlChat(idChat, invitado);
    }

    public void abondanarChat(String clave) {

        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlChatWSService");
        CtrlChatWS ctrl = new CtrlChatWSService(dir, qNa).getCtrlChatWSPort();
        ctrl.abandonarChat(idChat, clave);

    }

    class Leer extends Thread {

        @Override
        public void run() {
            while (true) {
                
                leer();
            }
        }
    };
    
     
     

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Conversacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Conversacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Conversacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Conversacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Conversacion dialog = new Conversacion(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    public ArrayList<DataMensaje> getBandejaSalida() {
        return bandejaSalida;
    }

    public void setBandejaSalida(ArrayList<DataMensaje> bandejaSalida) {
        this.bandejaSalida = bandejaSalida;
    }

    public int getIdChat() {
        return idChat;
    }

    public void setIdChat(int idChat) {
        this.idChat = idChat;
    }

//    public ArrayList<DataMensaje> getHistorialLocal() {
//        return historialLocal;
//    }
//
//    public void setHistorialLocal(ArrayList<DataMensaje> historialLocal) {
//        this.historialLocal = historialLocal;
//    }
//    

    public void enviarBandeja() {

        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlChatWSService");
        CtrlChatWS ctrl = new CtrlChatWSService(dir, qNa).getCtrlChatWSPort();

        Iterator<DataMensaje> it = bandejaSalida.iterator();

        while (it.hasNext()) {
            try {
                DataMensaje dm = it.next();
                ctrl.send(dm,idChat);
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(Conversacion.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        bandejaSalida.clear();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Abandonar;
    private javax.swing.JLabel charla;
    private javax.swing.JButton jButton1;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField mensaje;
    private javax.swing.JButton recibir;
    // End of variables declaration//GEN-END:variables
}
